<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ this.$router.currentRoute.name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-page-header @back="goBack"
                      :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>
      <!-- 系统通知列表卡片区 -->
      <el-form :inline="true" ref="form" :model="queryMap" size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <div class="block" style="margin-bottom: 1vh">
          <span class="demonstration" style="color: #1f2d3d;line-height: 4vh;font-size: 14px;">创建时间: </span>
          <el-date-picker
              @change="handleDateChange"
              v-model="queryDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="height: 4vh;margin-right: 2vh"
              :picker-options="pickerOptions">
          </el-date-picker>
          <el-form-item label="选择账号:">
            <el-select
                style="width: 160px;"
                v-model="queryMap.accountName"
                filterable
                @change="searchResource"
                placeholder="请选择账号"
            >
              <el-option
                  :key="0"
                  label="全部"
                  :value="null"
              >
              </el-option>
              <el-option
                  v-for="(name) in accountName"
                  :key="name"
                  :label="name"
                  :value="name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否已分配归属:">
            <el-select
                style="width: 160px;"
                v-model="queryMap.userId"
                filterable
                placeholder="请选择"
            >
              <el-option
                  key="0"
                  label="全部"
                  value="0"
              >
              </el-option>
              <el-option
                  key="-1"
                  label="未分配"
                  value="-1"
              >
              </el-option>
              <el-option
                  key="1"
                  label="已分配"
                  value="1"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
                style="width: 130px;"
                clearable
                v-model="queryMap.userName"
                placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                style="width: 150px;"
                clearable
                v-model="queryMap.taskPackageName"
                placeholder="请输入任务包名"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchResource()" icon="el-icon-search">查询</el-button>
          </el-form-item>
        </div>
      </el-form>

      <div style="margin-bottom: 2vh;display: flex">
        <span class="hint"
              style="font-size: 11px;line-height: 3vh;color: #555">任务分配 <span>共{{ total }}条</span></span>
        <span class="hint" style="flex: 1;font-size: 11px;line-height: 3vh">温馨提示：资源数据保存周期为30天，超过30天的无效、未标记数据将会被删除。单个任务资源数量不超过5万条。</span>
        <el-button size="mini" icon="el-icon-connection"
                   v-hasPermission="'taskpackage_resource:findDuplicate'"
                   @click="findDuplicatePhones(0)">批量去重
        </el-button>
        <el-button size="mini" icon="el-icon-connection"
                   v-hasPermission="'taskpackage_resource:findDuplicate'"
                   @click="findDuplicatePhones(1)">全部去重
        </el-button>
        <!--        v-hasPermission="'taskpackage_resource:downloadTemplate'"-->
        <el-button size="mini"
                   @click="isVisible=true" icon="el-icon-info">下载模板
        </el-button>
        <el-button size="mini"
                   v-hasPermission="'task_package:add'"
                   @click="drawer = true" icon="el-icon-circle-plus">新增
        </el-button>
      </div>
      <!-- 表格区域 -->
      <el-table ref="multipleTable"
                v-loading="tableLoading"
                size="small"
                :data="sysNoticeList"
                @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="taskPackageId" label="任务包编号" width="100"></el-table-column>
        <el-table-column prop="taskPackageName" label="任务名称" fixed="left" width="200"></el-table-column>
        <el-table-column prop="userName" label="创建人" width="100"></el-table-column>
        <el-table-column prop="accountName" label="创建人账户" width="100"></el-table-column>
<!--        <el-table-column prop="artificialCalling" label="人工已呼" width="100"></el-table-column>-->
<!--        <el-table-column prop="notCalling" label="未呼" width="100"></el-table-column>-->
<!--        <el-table-column prop="assignedQuantity" label="已分配数量" width="200"></el-table-column>-->
<!--        <el-table-column prop="resourceTotal" label="资源总数" width="200"></el-table-column>-->
        <el-table-column  prop="artificialCalling" label="任务包详情" width="100">
          <template slot-scope="scope">
            <el-popover
                placement="top"
                width="400"
                trigger="click"
                @show="getInfoById(scope.row.taskPackageId)"
            >
              <el-table :data="taskPackageDate"  v-loading=" popoverLoading">
                <el-table-column prop="artificialCalling" label="人工已呼" width="100"></el-table-column>
                <el-table-column prop="notCalling" label="未呼" width="100"></el-table-column>
                <el-table-column prop="assignedQuantity" label="已分配数量" width="100"></el-table-column>
                <el-table-column prop="resourceTotal" label="资源总数" width="100"></el-table-column>
              </el-table>
              <el-button slot="reference">详情</el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200"></el-table-column>
        <el-table-column label="操作" fixed="right" width="510">
          <template v-slot="scope">
            <el-button type="info" size="mini" @click="toUnDistributed(scope)" plain>未分配</el-button>
            <el-button type="primary" size="mini" @click="toAllocated(scope)" plain>已分配</el-button>
            <el-button type="primary" size="mini"
                       v-hasPermission="'taskpackage_resource:batch'"
                       @click="onTaskPackageId(scope.row.taskPackageId,scope.row.accountName);">全部分配
            </el-button>
            <el-tooltip content="分配任务包归属" placement="top" effect="light">
              <el-button type="primary" size="mini"  icon="el-icon-s-unfold"
                         v-hasPermission="'taskpackage_resource:batch++'"
                         @click="onTaskPackage(scope.row.taskPackageId);"  plain circle ></el-button>
            </el-tooltip>
            <el-tooltip content="回收" placement="top" effect="light">
              <el-button type="primary" v-hasPermission="'taskpackage_resource:recycle'"
                         size="small" icon="el-icon-s-help"
                         @click="recycleResources(scope.row.taskPackageId)" plain circle></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" v-hasPermission="'taskpackage_resource:delete'"
                         size="small" icon="el-icon-delete"
                         @click="del(scope.row.taskPackageId, scope.row.assignedQuantity)" plain circle></el-button>
            </el-tooltip>
            <el-tooltip content="导入" placement="top" effect="light">
              <el-button size="small"
                         v-hasPermission="'taskpackage_resource:import'"
                         @click="()=>{downTaskPackageId=scope.row.taskPackageId;isVisible_upload=true}"
                         icon="el-icon-upload2" plain circle></el-button>
            </el-tooltip>
            <el-tooltip content="导出所有数据" placement="top" effect="light">
              <el-button size="small"
                         v-hasPermission="'taskpackage_resource:export'"
                         icon="el-icon-download" plain circle
                         @click="downExcel(scope.row.taskPackageId)"></el-button>
            </el-tooltip>
            <el-tooltip content="去重" placement="top" effect="light">
              <el-button size="small"
                         v-hasPermission="'taskpackage_resource:findDuplicate'"
                         icon="el-icon-connection"
                         @click="()=>{multipleSelection.push({taskPackageId:scope.row.taskPackageId}); findDuplicatePhones(0)}"
                         plain circle></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>


      <!-- 选择用户窗口 -->
      <ElectUsersBox title="资源分配" @confirmUserId="confirmResourcesId" :isShow="electUsersBoxShow"
                     @updateElectUsersBoxShow="electUsersBoxShow=false"/>
      <!-- 选择用户窗口 -->
      <ElectUsersBox title="任务包分配(仅展示管理员)" @confirmUserId="confirmUser" :termMap="{isGetAdmin:true}" :isRadio="true" :isShow="electUsersBoxShow2" @updateElectUsersBoxShow="electUsersBoxShow2=false"/>

      <!-- 下载模板弹出层 -->
      <div v-if="isVisible" class="popups" @click.self="isVisible=false">
        <el-main style="width: 22vw;height: 22vh">
          <div class="header">
            <h3 style="flex: 1">下载模板</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle @click="isVisible=false"></el-button>
            </el-tooltip>
          </div>
          <div>
            <!--              <el-button icon="el-icon-info" size="big">快速模板</el-button>-->
            <el-button icon="el-icon-info" size="big" @click="downloadTemplate">标准模板</el-button>
          </div>
        </el-main>
      </div>

      <!-- 新增右边抽屉 -->
      <el-drawer
          title="新增任务包"
          :visible.sync="drawer"
          direction="rtl"
          size="30%"
          :before-close="handleClose">
        <div v-loading="btnLoading">
          <div style="padding: 0 3vw 0 3vw;height: 83vh;overflow-y: auto;">
            <el-form :model="addTask" label-width="80px" size="small">

              <el-form-item label="任务包名">
                <el-input v-model="addTask.addTaskName" placeholder="请输入任务包名称" clearable></el-input>
              </el-form-item>

              <!--归属人-->
              <el-form-item label="归属人">
                <el-select v-model="addTask.userId" clearable filterable placeholder="请选择归属人">
                  <el-option
                      v-for="(item, index) in tableData"
                      :key="index"
                      :label="item.userName"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="模版类型:">
                <!--             <el-button icon="el-icon-info" @click="" >快速模板</el-button>-->
                <el-button icon="el-icon-info" @click="downloadTemplate">标准模板</el-button>
              </el-form-item>

              <!--上传excel文件-->
              <el-form-item label="数据文件">
              <el-upload
                  ref="upload"
                    class="upload-demo"
                    action="https://jsonplaceholder.typicode.com/posts/"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                    :on-change="handleFileChange"
                  :file-list="fileList"
                    :limit="1"
                  :auto-upload="false"
                    :on-progress="onProgress"
                    accept=".xlsx, .xls"
                >
                  <el-button slot="trigger" type="primary">点击上传</el-button>
                  <div class="el-upload__tip" slot="tip">只能上传.xlsx/xls文件，且不超过100MB</div>
              </el-upload>
              </el-form-item>

              <!-- 添加文件上传和导入进度显示区域 -->
              <div v-if="isUploading || importStatus !== ''">
                <el-divider content-position="left">上传进度</el-divider>
                <el-progress
                    :percentage="uploadProgress"
                  :status="uploadStatus"
                  :format="p => `${p}%`"
                  :stroke-width="18"
                ></el-progress>
                <div class="progress-info">{{progressInfo}}</div>

                <el-divider content-position="left" v-if="importStatus !== ''">导入进度</el-divider>
                <el-progress
                  v-if="importStatus !== ''"
                    :percentage="importProgress"
                  :status="importStatus"
                  :format="p => `${p.toFixed(2)}%`"
                  :stroke-width="18"
                ></el-progress>
                <div class="progress-info" v-if="importStatus !== ''">{{importInfo}}</div>
                
                <el-divider></el-divider>
              </div>

            </el-form>
          </div>
          <div  style="margin-left: 20px" class="demo-drawer__footer" v-if="!isUploading && importStatus !== 'running'">
            <el-button @click="closeDrawer">取消</el-button>
            <el-button icon="el-icon-circle-check" type="primary" size="big" @click="handleLargeFileUpload" :loading="btnLoading" :disabled="btnDisabled">
              保存
            </el-button>
          </div>
        </div>
      </el-drawer>


      <!-- 上传标签弹出层 -->
      <div v-if="isVisible_upload" class="popups" @click.self="isVisible_upload=false">
        <el-main style="width: 32.5vw;height: 56vh">
          <div class="header">
            <h3 style="flex: 1">导入资源</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle @click="isVisible_upload=false"></el-button>
            </el-tooltip>
          </div>
          <div style="padding-left: 7vh;height: 5vh">
            <span>选择账号:</span>
            <el-select
                style="width: 240px;"
                v-model="queryMap.accountName"
                filterable
                placeholder="请选择账号"
                default-first-option
            >
              <el-option
                  v-for="(name) in accountName"
                  :key="name"
                  :label="name"
                  :value="name">
              </el-option>
            </el-select>
          </div>
<!--          <div style="padding-left: 7vh;height: 5vh">-->
<!--            <span>归属人:</span>-->
<!--            <el-select v-model="addTask.userId" style="width: 250px;" filterable placeholder="请选择归属人">-->
<!--              <el-option-->
<!--                  v-for="item in tableData"-->
<!--                  :key="item.userId"-->
<!--                  :label="item.userName + '('+ item.nickName +')'"-->
<!--                  :value="item.userId">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--            <span style="color: red"> *</span>-->
<!--          </div>-->
          <div style="padding-left: 7vh;height: 29.2vh">
            <el-upload
                class="upload-demo"
                :auto-upload="false"
                drag
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :on-error="handleError"
                :file-list="fileList"
                multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传xls,xlsx文件，且不超过5M</div>
            </el-upload>
          </div>
          <el-button type="primary" size="medium" @click="submitLargeUpload"
                     :loading="btnLoading" :disabled="btnDisabled"
                     style="margin: 2vh 0 0 43vh;">确认
          </el-button>
        </el-main>
      </div>

    </el-card>
  </div>
</template>
<script>
import MenuTree from "../../../components/MenuTree"; //引进菜单模板
import axios from "axios";
import ElectUsersBox from "@/components/electUsersBox.vue";

export default {
  data() {
    // 计算最近一周的起始和结束日期
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
    end.setTime(end.getTime() + 3600 * 1000 * 24 * 1); // 当前时间减去 7 天
    return {
      // ... 其他已有变量

      // 文件上传相关
      uploadProgress: 0,
      uploadStatus: '',
      progressInfo: '',
      isUploading: false,
      
      // 导入进度相关
      importStatus: '',
      importProgress: 0,
      importInfo: '',
      progressCheckInterval: null,
      
      // 文件分片上传
      chunkSize: 50 * 1024 * 1024, // 50MB
      chunks: [],
      currentChunk: 0,
      file: null,
      mergedFilename: '',
      uploadId: null,

      popoverLoading:false,
      isVisible_upload: false,
      electUsersBoxShow: false,
      electUsersBoxShow2:false,
      btnLoading: false,
      btnDisabled: false,
      tableLoading: false,
      drawer: false,//右边抽屉是否展示
      isVisible: false,//下载模板弹出层是否展示
      sysNoticeList: [],
      loading: true,
      total: 0,
      multipleSelection: [],//多选id
      tableData: [],//用户列表
      //查询对象
      queryMap: {
        resourceTotal: "",
        taskPackageId: "",
        taskPackageName: "",
        userId: "",
        createTime: "",
        userName: "",
        accountName: "",
        addAccountName: "",
        assignedQuantity: "",
        artificialCalling: "",
        notCalling: "",
        pageNum: 1,
        pageSize: 10,
        startDate: start,
        endDate: end,
      },
      downTaskPackageId: 0,
      addTask: {
        addTaskName: "",
        userId: "",
        accountName: "",
      },
      accountName:[],
      taskPackageId: [],
      taskPackageDate:[{
        artificialCalling: 0,
        notCalling: 0,
        assignedQuantity: 0,
        resourceTotal: 0
      }],
      queryDate: [start, end],
      batchAllocationMap: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 上传文件列表
      fileList: [],
      excelFile: {},
      startTime: null,
    };
  },
  methods: {
    /**
     * 创建文件分片
     */
    async createFileChunks(file) {
      const chunks = [];
      const chunkSize = this.chunkSize;
      const totalSize = file.size;
      const chunkCount = Math.ceil(totalSize / chunkSize);
      
      this.uploadId = Date.now().toString();
      
      for (let i = 0; i < chunkCount; i++) {
        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, totalSize);
        chunks.push({
          blob: file.slice(start, end),
          index: i,
          total: chunkCount
        });
      }
      
      return chunks;
    },
    
    /**
     * 上传单个分片
     */
    async uploadChunk(chunk) {
      try {
      const formData = new FormData();
        formData.append('chunk', chunk.blob);
        formData.append('index', chunk.index);
        formData.append('total', chunk.total);
        formData.append('filename', this.file.name);
        // 传递uploadId，确保后续分片使用相同的ID
        if (this.uploadId) {
          formData.append('uploadId', this.uploadId);
        }
        
        const { data: res } = await this.$http.post('/tasking/uploadChunk', formData, {
            headers: {
            'Content-Type': 'multipart/form-data'
          }
          });
        
      if (res.success) {
          // 保存返回的uploadId供后续分片使用
          if (chunk.index === 0) {
            this.uploadId = res.data.uploadId;
          }
          
          // 更新上传进度
          this.uploadProgress = Math.floor((chunk.index + 1) / chunk.total * 100);
          this.progressInfo = `正在上传分片 ${chunk.index + 1}/${chunk.total}...`;
          return true;
      } else {
          this.progressInfo = '分片上传失败: ' + res.message;
          this.$message.error('分片上传失败: ' + res.message);
          return false;
        }
      } catch (error) {
        this.progressInfo = '分片上传失败: ' + error.message;
        this.$message.error('分片上传失败: ' + error.message);
        return false;
      }
    },
    
    /**
     * 上传所有分片
     */
    async uploadChunks() {
      this.isUploading = true;
      this.uploadStatus = 'warning'; // 使用warning表示进行中
      this.progressInfo = '准备上传...';
      
      for (let i = 0; i < this.chunks.length; i++) {
        this.currentChunk = i;
        const success = await this.uploadChunk(this.chunks[i]);
        if (!success) {
          this.uploadStatus = 'exception';
          this.isUploading = false;
        return false;
      }
      }
      
      // 所有分片上传完成，合并文件
      this.progressInfo = '所有分片上传完成，正在合并文件...';
      const merged = await this.mergeChunks();
      
      return merged;
    },
    
    /**
     * 合并文件分片
     */
    async mergeChunks() {
      try {
        const { data: res } = await this.$http.post('/tasking/mergeChunks', {
          filename: this.file.name,
          uploadId: this.uploadId,
          totalChunks: this.chunks.length
        });
        
        if (res.success) {
          this.uploadStatus = 'success';
          this.progressInfo = '文件合并成功，准备导入数据...';
          this.mergedFilename = res.data.mergedFilename;
          return true;
        } else {
          this.uploadStatus = 'exception';
          this.progressInfo = '文件合并失败: ' + res.message;
          this.$message.error('文件合并失败: ' + res.message);
          return false;
        }
      } catch (error) {
        this.uploadStatus = 'exception';
        this.progressInfo = '文件合并失败: ' + error.message;
        this.$message.error('文件合并失败: ' + error.message);
        return false;
      }
    },

    accountNameChange(){
      this.queryMap.userId=null;
      this.addTask.userId=null;
      this.selectUser();
    },
    /**
     * 加载任务包列表
     */
    async getAllTaskPackage() {
      this.tableLoading = true;
      const {data: res} = await this.$http.get("/tasking/taskgoverning/getAllTaskPackage", {
        params: this.queryMap
      });
      if (!res.success) {
        this.tableLoading = false;
        return this.$message.error("获取任务包列表失败:" + res.data.errorMsg);
      }
      this.total = res.data.total;
      this.sysNoticeList = res.data.rows;
      this.loading = false;
      this.tableLoading = false;
    },
    /**
     * 根据id查询任务包详情
     * @param id 任务包id
     */
    async getInfoById(id){
      this.taskPackageDate = [{
        artificialCalling: 0,
        notCalling: 0,
        assignedQuantity: 0,
        resourceTotal: 0
      }];
      //让表格处于加载状态
      this.popoverLoading=true;
      const { data: res } = await this.$http.get("/tasking/taskgoverning/getTaskPackageById/"+id);
      if(res.success){
        this.taskPackageDate = [{
          artificialCalling: res.data.artificialCalling,
          notCalling: res.data.notCalling,
          assignedQuantity: res.data.assignedQuantity,
          resourceTotal: res.data.resourceTotal
        }];
        //让表格处于非加载状态
        this.popoverLoading=false;
      } else {
        //让表格处于非加载状态
        this.popoverLoading=false;
        return this.$message.error("任务包详情信息获取失败:" + res.message);
      }
    },
    /**
     * 加载用户列表
     */
    async selectUser() {
      const {data: res} = await this.$http.post("/system/departmentUtils/getUserListByMap/", {
        accountName : this.queryMap.addAccountName
      });
      if (res.success) {
        this.tableData = res.data;
      } else {
        return this.$message.error("用户列表查询失败:" + res.message);
      }
    },
    /**
     * 获得账号信息
     */
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data.errorMsg);
      }
      this.accountName = res.data
      // if (this.accountName.length > 0) {
      //   this.queryMap.accountName = this.accountName[0];
      //   this.queryMap.addAccountName = this.accountName[0];
      // }
    },
    /**
     * 当时间选择时，直接赋值
     * @change="handleDateChange" 将其添加到时间中
     */
    handleDateChange() {
      this.queryMap.startDate = this.formatDate(this.queryDate[0], false);
      this.queryMap.endDate = this.formatDate(this.queryDate[1], true);
      this.selectUser();
    },
    /**
     * 搜索任务包
     */
    async searchResource() {
      this.tableLoading = true;
      this.queryMap.pageNum = 1;
      await this.getAllTaskPackage();
      this.tableLoading = false;
    },
    /**
     * 将任务包编号传入data
     */
    onTaskPackageId(taskPackageId,accountName) {
      if (accountName==null){
        this.$message.warning("该任务包无归属账户，请先分配归属账户");
        return;
      }
      this.taskPackageId = taskPackageId;
      this.confirmResourcesId();
    },
    /**
     * 将任务包编号传入data
     */
    onTaskPackage(taskPackageId){
      this.taskPackageId=taskPackageId;
      //展示弹窗
      this.electUsersBoxShow2=true

    },
    /**
     * 批量分配
     */
    async confirmResourcesId(uIds) {
      //展示弹窗
      this.electUsersBoxShow = true
      const createBatchAllocationMap = (uIds) => ({
        userIds: uIds,
      });
      const taskPackageId = this.taskPackageId;
      this.batchAllocationMap = createBatchAllocationMap(uIds);

      // 当用户确认分配时，发送请求
      if (uIds.length > 0) {
        this.tableLoading = true;
        const {data: res} = await this.$http.post("/tasking/batchAllocationResource/" + taskPackageId, this.batchAllocationMap);
        if (res.data === "success") {
          this.$message.success("分配资源成功");
        } else if (res.data === "isNull") {
          this.$message.warning("已分配资源");
        } else if (res.data === "fail") {
          this.$message.warning("无未分配资源");
        } else {
          this.$message.error("分配资源失败:" + res);
        }
        // 重新加载数据
        await this.getAllTaskPackage();
      }
    },
    async confirmUser(ids){
      const { data: res } = await this.$http.post("/tasking/taskgoverning/updateTaskPackage", {
        taskPackageId:this.taskPackageId,
        userId:ids[0]
      })
      if (res.data === "success"  ) {
        this.$message.success("分配任务包成功");
        this.getAllTaskPackage();
      }else {
        this.$message.warning("分配失败，请联系管理员");
      }
    },
    /**
     * 加载任务包表格
     * 导出任务包数据
     */
    downExcel(taskPackageId) {
      const $this = this;
      const res = axios
          .request({
            url: "http://47.99.186.44:8989/tasking/excel/" + taskPackageId,
            method: "post",
            responseType: "blob",
            headers: {'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)},	//设置请求头
          })
          .then(res => {
            if (res.headers["content-type"] === "application/json") {
              return $this.$message.error(
                  "Subject does not have permission [task:export]"
              );
            }
            if (res.data == "IsNull") {
              return $this.$message.error("该任务包无已分配资源");
            }
            const data = res.data;
            let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "任务资源列表.xls";
            a.click();
            window.URL.revokeObjectURL(url);
          }).catch(err => {
            console.log(err);
            //当返回404时
            if (err.response.status === 404) {
              return $this.$message.error("该任务包数据有误");
            }
          });
    },
    /**
     * 回收
     */
    async recycleResources(taskPackageId) {
      console.log(taskPackageId)
      const flag = await this.$confirm(
          "此操作将回收该任务包的所有资源, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消回收"
        });
      });
      if (flag === "confirm") {
        this.tableLoading = true;
        // 使用RequestBody方式发送POST请求，配置请求体传递数据
        try {
          const {data: res} = await this.$http.post("/tasking/batchRecycleResources", taskPackageId);
          if (res.data === "success") {
            this.$message.success("回收资源成功");
          } else if (res.data === "isNull") {
            this.$message.warning("无已分配资源");
          } else {
            this.$message.error("回收资源失败: " + res);
          }
          // 重新加载数据
          await this.getAllTaskPackage();
        } catch (error) {
          // 处理请求过程中的网络错误等异常情况，假设error对象有message字段表示错误详情，具体按实际情况调整
          this.$message.error("回收资源请求出错: " + error.message);
        }
        // 重新加载数据
        await this.getAllTaskPackage();
      }
    },
    /**
     * 下载模板
     */
    downloadTemplate() {
      const $this = this;
      const res = axios.request({
        url: "http://47.99.186.44:8989/template/download",
        method: "post",
        responseType: "blob",
        headers: {
          'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)
        },
        data: {
          templateId: "file:/www/wwwroot/danebCRM/backEnd/client/static/TaskPackageResources.xls"
        }
      })
          .then(res => {
            if (res.headers["content-type"] === "application/json") {
              return $this.$message.error(
                  "Subject does not have permission [class:export]"
              );
            }
            const data = res.data;
            let url = window.URL.createObjectURL(data);
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "任务包资源模版.xlsx";
            a.click();
            window.URL.revokeObjectURL(url);
          })
          .catch(error => {
            console.error("下载出现错误：", error);
            this.$message.error("文件下载失败，请稍后再试");
          });
    },
    /**
     * 去重
     */
    async findDuplicatePhones(count) {
      // 根据count是否有值来确定不同的提示信息
      let confirmMessage = count === 1 ? "此操作将查重全部任务包资源，是否继续?" : "此操作将查重选中的任务包资源, 是否继续?";
      if (count === 1) {
        console.log("当前是选择全部查重");
      } else {
        if (this.multipleSelection.length < 1) {
          this.$message('未选择任务包');
          return;
        }
        console.log("当前是批量查重");
      }
      const flag = await this.$confirm(
          confirmMessage,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消查重操作"
        });
        // 清空id列表
        this.multipleSelection = [];
      });
      if (flag === "confirm") {
        // 使用RequestBody方式发送POST请求，配置请求体传递数据
        // 获取选中的资源id
        const ids = this.multipleSelection.map(row => row.taskPackageId);
        if (count === 1) {
          //将数组赋值清空
          ids.length = 0;
        }
        try {
          this.tableLoading = true;
          const {data: res} = await this.$http.post("/tasking/findDuplicatePhones", ids);
          if (res.message === "success") {
            this.$message.success("重复的任务包资源清理成功");
          } else if (res.message === "isNull") {
            this.$message.warning("无重复的任务包资源或者已被回收");
          } else {
            this.$message.error("查重任务包资源失败: " + res);
          }
        } catch (error) {
          // 处理请求过程中的网络错误等异常情况，假设error对象有message字段表示错误详情，具体按实际情况调整
          this.$message.error("查重任务包资源请求出错: " + error.message);
        } finally {
          // 清空id列表
          this.multipleSelection = [];
          // 重新加载数据
          await this.getAllTaskPackage();
        }
      }
    },
    /**
     * 重置
     */
    reset() {
      this.queryMap = {
        resourceTotal: "",
        taskPackageId: "",
        taskPackageName: "",
        userId: "",
        createTime: "",
        userName: "",
        assignedQuantity: "",
        artificialCalling: "",
        notCalling: "",
        pageNum: 1,
        pageSize: 10,
      }
      this.queryDate = [];
    },
    // 定义一个格式化时间的函数
    formatDate(date, is) {
      //判断时间是否为空
      if (date != null) {
        //判断是否为结束时间
        if (is) {
          date.setDate(date.getDate() + 1);
        }
        const year = date.getFullYear();
        //+1，是因为月份是从0开始
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        // console.log('格式化前各部分值: 年:', year,'月:', month,'日:', day);
        const hours = ('0' + date.getHours()).slice(-2);
        const minutes = ('0' + date.getMinutes()).slice(-2);
        const seconds = ('0' + date.getSeconds()).slice(-2);
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // console.log('最终返回结果:', result);
      }
      return null;
    },
    /**
     * 已分配跳转
     */
    toAllocated(scope) {
      const taskPackageId = scope.row.taskPackageId;
      this.$router.push({
        path: '/tasking/allocated',
        query: {taskPackageId}
      });
    },

    /**
     * 未分配跳转
     */
    toUnDistributed(scope) {
      const taskPackageId = scope.row.taskPackageId;
      this.$router.push({
        path: '/tasking/undistributed',
        query: {taskPackageId}
      });

    },
    /**
     * 删除任务包
     */
    async del(id, assignedQuantity) {
      // 先判断 this.queryMap.assignedQuantity 的数量
      if (assignedQuantity > 0) {
        this.$message({
          type: "warning",
          message: "请将分配的资源收回再进行删除操作"
        });
        return; // 如果数量大于0，直接返回，不执行后续删除逻辑
      }
      const res = await this.$confirm(
          "此操作将永久删除该任务包, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res === "confirm") {
        const {data: res} = await this.$http.delete("/tasking/taskgoverning/delByTaskPackageId/" + id);
        console.log(res);
        if (res.success) {
          this.$notify.success({
            title: '操作成功',
            message: '任务包及其数据删除成功',
          });
        } else {
          this.$message.error(res.data.errorMsg);
        }
      }
      await this.getAllTaskPackage();
    },
    /**
     * 全选功能
     *
     */
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("******************************", val);
    },
    confirmUserId(ids) {
      console.log(ids)
    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getAllTaskPackage();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getAllTaskPackage();
    },
    /**
     * 退一步
     */
    goBack() {
      console.log('go back');
      this.$router.go(-1);
    },
    // 添加被删除的 createTaskPackage 方法
    async createTaskPackage() {
      // 将当前addTask中userId对应的tableData赋值给addTask
      const selectedUser = this.tableData.find(user => user.userId === this.addTask.userId);
      if (selectedUser) {
        this.addTask.accountName = selectedUser.accountName;
      }
      //校验文档
      if (!await this.beforeUpload(this.excelFile.raw)) {
        return;
      }
      if (!this.addTask.addTaskName) {
        return this.$message.error("任务包名称不能为空");
      }
      // if (!this.addTask.userId) {
      //   return this.$message.error("请选择归属人");
      // }
      // 创建 FormData 对象
      const formData = new FormData();
      formData.append("file", this.excelFile.raw);
      formData.append("taskPackageName", this.addTask.addTaskName);
      if (this.addTask.userId!=null){
        formData.append("userId", this.addTask.userId);
      }
      if (this.addTask.accountName!=null){
        formData.append("accountName", this.addTask.accountName);
      }

      console.log(formData)
      this.btnLoading = true;
      this.btnDisabled = true;
      this.tableLoading = true;
      const {data: res} = await this.$http.post("/tasking/addTaskPackage", formData
          , {
            headers: {
              "Content-Type": "multipart/form-data", // 确保是多部分请求
            },
          });
      if (res.success) {
        this.$notify.success({
          title: '操作成功',
          message: '任务包创建成功',
        });
      } else {
        this.drawer = false;
        this.btnLoading = false;
        this.btnDisabled = false;
        this.tableLoading = false;
        if (res.data==null){
          return this.$message.error("任务包创建失败:" +  res.message);
        }
        return this.$message.error("任务包创建失败:" + res.data.errorMsg);
      }
      //关闭抽屉
      this.drawer = false;
      this.btnLoading = false;
      this.btnDisabled = false;
      this.tableLoading = false;
      //清空抽屉文件集合
      this.fileList = [];
      this.excelFile = {};
      this.addTask = {};
      this.addName = [];
      //调用查询方法
      await this.searchResource();
    },
    // 添加格式化文件大小的方法
    formatSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
    },
    // 修改上传进度处理方法
    onProgress(event, file) {
      if (!this.chunks.length) { // 文件直接上传的情况
        this.uploadProgress = Math.floor(event.percent);
        this.progressInfo = `已上传 ${this.formatSize(event.loaded)} / ${this.formatSize(file.size)}`;
      }
    },
    /**
     * 处理文件变更事件
     */
    handleFileChange(file) {
      if (file.status === 'ready') {
        this.excelFile = file;
        this.file = file.raw;
        // 验证文件类型
        const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                        file.raw.type === 'application/vnd.ms-excel';
        if (!isExcel) {
          this.$message.error('只能上传 .xls 或 .xlsx 格式的文件');
          this.fileList = [];
          this.file = null;
          return false;
        }
        
        // 验证文件大小
        const isLt100MB = file.raw.size / 1024 / 1024 < 100;
        if (!isLt100MB) {
          this.$message.error('文件大小不能超过 100MB!');
          this.fileList = [];
          this.file = null;
          return false;
        }
      }
      
      return true;
    },
    
    /**
     * 处理大文件上传
     */
    async handleLargeFileUpload() {
      if (!this.file) {
        return this.$message.error('请选择文件');
      }
      
      if (!this.addTask.addTaskName) {
        return this.$message.error('请输入任务包名称');
      }
      
      // 校验文件类型
      const isExcel = this.file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                      this.file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        return this.$message.error('只能上传 .xls 或 .xlsx 格式的文件');
      }
      
      // 将当前addTask中userId对应的tableData数据的accountName赋值给addTask
      const selectedUser = this.tableData.find(user => user.userId === this.addTask.userId);
      if (selectedUser) {
        this.addTask.accountName = selectedUser.accountName;
      }
      
      // 记录开始时间
      this.startTime = Date.now();
      
      // 开始上传前，设置通用的状态
      this.btnLoading = true;
      this.btnDisabled = true;
      this.isUploading = true;
      this.uploadStatus = 'warning'; // 使用warning表示进行中
      this.progressInfo = '准备上传文件...';
      
      try {
        // 根据文件大小决定使用哪种上传方式
        if (this.file.size > this.chunkSize) {
          // 大文件分片上传
          // 创建文件分片
          this.chunks = await this.createFileChunks(this.file);
          
          // 上传分片
          const uploadSuccess = await this.uploadChunks();
          if (!uploadSuccess) {
            this.btnLoading = false;
            this.btnDisabled = false;
            this.isUploading = false;
            return;
          }
          
          // 开始创建任务包
          await this.submitLargeTaskPackage();
        } else {
          // 文件直接提交，但也显示进度
          // 模拟上传进度
          this.uploadProgress = 0;
          
          // 使用定时器模拟上传进度增加
          const progressInterval = setInterval(() => {
            if (this.uploadProgress < 90) {
              this.uploadProgress += 10;
              this.progressInfo = `正在上传文件 ${this.uploadProgress}%...`;
            } else {
              clearInterval(progressInterval);
            }
          }, 200);
          
          try {
            // 创建FormData对象
            const formData = new FormData();
            formData.append("file", this.file);
            formData.append("taskPackageName", this.addTask.addTaskName);
            
            if (this.addTask.accountName) {
              formData.append("accountName", this.addTask.accountName);
            }
            
            if (this.addTask.userId) {
              formData.append("userId", this.addTask.userId);
            }
            
            this.progressInfo = '正在上传文件...';
            console.log('开始上传文件并创建任务包:', this.file.name, '文件大小:', this.formatSize(this.file.size));
            
            // 使用合并的接口直接上传文件并创建任务包
            const { data: res } = await this.$http.post("/tasking/uploadFileAndCreatePackage", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            });
            
            if (!res.success) {
              console.error('文件上传或任务包创建失败:', res);
              throw new Error(res.message || res.data && res.data.message || '上传或创建失败');
            }
            
            console.log('文件上传和任务包创建成功');
            this.progressInfo = '文件上传完成，正在导入数据...';
            this.uploadProgress = 100;
            this.uploadStatus = 'success';
            
            // 设置导入状态
            this.importStatus = 'warning'; // 使用warning表示进行中
            this.importProgress = 0;
            this.importInfo = '数据导入中...';
            
            // 获取任务包ID
            const taskPackageId = res.data.taskPackageId;
            if (!taskPackageId) {
              throw new Error('未能获取任务包ID');
            }
            
            console.log('任务包创建成功，ID:', taskPackageId);
            
            // 开始检查导入进度
            this.startTaskImportProgressCheck(taskPackageId);

          } catch (error) {
            this.importStatus = 'exception';
            this.importInfo = '操作失败: ' + error.message;
            this.$message.error('上传或创建任务包失败: ' + error.message);
          } finally {
            // 清除之前的进度定时器
            clearInterval(progressInterval);
            this.btnLoading = false;
            this.btnDisabled = false;
          }
        }
      } catch (error) {
        this.uploadStatus = 'exception';
        this.progressInfo = '上传失败: ' + error.message;
        this.$message.error('上传失败: ' + error.message);
        this.btnLoading = false;
        this.btnDisabled = false;
        this.isUploading = false;
      }
    },
    
    /**
     * 关闭抽屉
     */
    closeDrawer() {
      // 如果有正在进行的上传或导入，弹出确认框
      if (this.isUploading || this.importStatus === 'running') {
        this.$confirm('正在进行文件上传或数据导入，确定要取消吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 清除定时器
          if (this.progressCheckInterval) {
            clearInterval(this.progressCheckInterval);
            this.progressCheckInterval = null;
          }
          this.resetUploadStatus();
          this.drawer = false;
        }).catch(() => {
          // 取消关闭
        });
      } else {
        this.resetUploadStatus();
        this.drawer = false;
      }
    },
    
    /**
     * 重置上传状态
     */
    resetUploadStatus() {
      this.isUploading = false;
      this.uploadProgress = 0;
      this.uploadStatus = ''; // 使用空字符串
      this.progressInfo = '';
      this.importStatus = ''; // 使用空字符串
      this.importProgress = 0;
      this.importInfo = '';
      this.chunks = [];
      this.currentChunk = 0;
      this.file = null;
      this.mergedFilename = '';
      this.uploadId = null;
      this.fileList = [];
      this.excelFile = {};
    },
    
    /**
     * 抽屉关闭前回调
     */
    handleClose(done) {
      this.closeDrawer();
    },
    /**
     * 提交创建任务包 - 大文件处理方式
     */
    async submitLargeTaskPackage() {
      if (!this.file) {
        return this.$message.error('请选择文件');
      }
      
      if (!this.addTask.addTaskName) {
        return this.$message.error('请输入任务包名称');
      }
      
      // 创建任务包 - 这里需要后端提供专门的大文件任务包创建接口
      try {
        // 记录开始时间
        this.startTime = Date.now();
        
        const { data: res } = await this.$http.post('/tasking/createLargeTaskPackage', {
          mergedFilename: this.mergedFilename,
          taskPackageName: this.addTask.addTaskName,
          userId: this.addTask.userId || null,  // 确保空字符串变为null
          accountName: this.addTask.accountName || ''
        });
        
        if (res.success) {
          // 获取任务包ID
          const taskPackageId = res.data.taskPackageId;
          
          // 开始检查导入进度
          this.importStatus = 'warning'; // 改为warning表示进行中
          this.importProgress = 0;
          this.importInfo = '任务包创建中...';
          
          // 开始定时检查导入进度
          this.startTaskImportProgressCheck(taskPackageId);
          
          // 关闭抽屉
          //this.drawer = false;
        } else {
          this.btnLoading = false;
          this.btnDisabled = false;
          return this.$message.error('任务包创建失败: ' + res.message);
        }
      } catch (error) {
        this.btnLoading = false;
        this.btnDisabled = false;
        return this.$message.error('任务包创建请求失败: ' + error.message);
      }
    },
    
    /**
     * 定时检查任务包导入进度
     */
    startTaskImportProgressCheck(taskPackageId) {
      // 清除可能存在的定时器
      if (this.progressCheckInterval) {
        clearInterval(this.progressCheckInterval);
      }
      
      // 创建新的定时器
      this.progressCheckInterval = setInterval(async () => {
        await this.checkTaskImportProgress(taskPackageId);
      }, 2000); // 每2秒检查一次
    },
    
    /**
     * 检查任务包导入进度
     */
    async checkTaskImportProgress(taskPackageId) {
      try {
        //console.log('检查任务包导入进度，ID:', taskPackageId);
        const { data: res } = await this.$http.get(`/tasking/importStats/${taskPackageId}`);
        
        if (res.success) {
          const stats = res.data;
          //console.log('获取到导入进度:', stats);
          
          // 更新上传和导入信息
          if (stats.status === 'completed') {
            // 导入完成
            this.importProgress = 100;
            this.importStatus = 'success';

            // 构建结果信息
            const resultMsg = `上传${stats.uploadTimeSeconds?.toFixed(2) || 0}秒, 文件共${stats.totalRows || 0}行，成功导入${stats.importedRows || 0}条记录，耗时${stats.importTimeSeconds?.toFixed(2) || 0}秒`;
            this.importInfo = resultMsg;
            
            // 使用统计信息显示成功提示
            this.$message.success(resultMsg);
            
            // 清除定时器
            clearInterval(this.progressCheckInterval);
            this.progressCheckInterval = null;
            
            // 刷新任务包列表
            this.searchResource();
            
            // 解除按钮加载状态
            this.btnLoading = false;
            this.btnDisabled = false;
          } else if (stats.status === 'error') {
            // 导入出错
            this.importStatus = 'exception';
            this.importInfo = '导入失败: ' + (stats.errorMessage || '未知错误');
            this.$message.error('导入失败: ' + (stats.errorMessage || '未知错误'));
            
            // 清除定时器
            clearInterval(this.progressCheckInterval);
            this.progressCheckInterval = null;
            
            // 解除按钮加载状态
            this.btnLoading = false;
            this.btnDisabled = false;
          } else if (stats.status === 'partial_error') {
            // 部分记录导入成功，有错误
            this.importProgress = 100;
            this.importStatus = 'warning';
            
            const resultMsg = `文件共${stats.totalRows || 0}行，成功导入${stats.importedRows || 0}条记录，有部分批次失败`;
            this.importInfo = resultMsg + (stats.errorMessage ? '，错误: ' + stats.errorMessage : '');
            
            // 显示警告
            this.$notify.warning({
              title: '部分导入成功',
              message: resultMsg,
              duration: 8000
            });
            
            // 清除定时器
            clearInterval(this.progressCheckInterval);
            this.progressCheckInterval = null;
            
            // 刷新任务包列表
            this.searchResource();
            
            // 解除按钮加载状态
            this.btnLoading = false;
            this.btnDisabled = false;
          } else if (stats.status === 'importing') {
            // 导入处理中，更新进度
            const progress = stats.progress || 0;
            this.importProgress = progress;
            // 确保状态为warning
            this.importStatus = 'warning';

            // 构建详细的进度信息
            this.importInfo = `上传耗时${stats.uploadTimeSeconds?.toFixed(2) || 0}秒, 正在导入中(${progress.toFixed(2)}%)...
                            已处理${stats.processedRows || 0}/${stats.totalRows || 0}行, 已导入${stats.importedRows || 0}条`;
          } else if (stats.status === 'uploading') {
            // 文件上传中
            this.importStatus = 'warning'; // 确保状态为warning
            this.importInfo = `文件上传中...`;
          }
        } else if (res.message && res.message.includes('未找到')) {
          // 设置等待进度，避免用户看到0%很久
          console.log('任务包进度信息未就绪，继续等待...');
          // 增加等待进度，每次增加1%直到90%
          if (this.importProgress < 90) {
            this.importProgress += 1;
          }
          this.importInfo = `正在处理数据...已等待${Math.floor((Date.now() - this.startTime) / 1000)}秒`;
          
          // 设置超时处理，如果等待超过2分钟还没有进度，提示可能出错
          const elapsedSeconds = Math.floor((Date.now() - this.startTime) / 1000);
          if (elapsedSeconds > 120 && this.importProgress < 10) {
            this.errorCount = (this.errorCount || 0) + 1;
            if (this.errorCount >= 5) {
              this.importStatus = 'exception';
              this.importInfo = '长时间无法获取导入进度，处理可能已失败，请检查服务器日志';
              clearInterval(this.progressCheckInterval);
              this.progressCheckInterval = null;
              this.btnLoading = false;
              this.btnDisabled = false;
              
              this.$message.error('导入处理超时，请检查服务器日志或联系管理员');
            }
          }
        } else {
          console.error('获取导入进度失败:', res.message);
          this.errorCount = (this.errorCount || 0) + 1;
          
          if (this.errorCount >= 5) {
            this.importStatus = 'exception';
            this.importInfo = '获取导入进度失败: ' + res.message;
            clearInterval(this.progressCheckInterval);
            this.progressCheckInterval = null;
            this.btnLoading = false;
            this.btnDisabled = false;
          }
        }
      } catch (error) {
        console.error('检查导入进度出错:', error);
        // 错误计数，连续5次错误后停止
        this.errorCount = (this.errorCount || 0) + 1;
        if (this.errorCount >= 5) {
          this.importStatus = 'exception';
          this.importInfo = '无法获取导入进度，请检查网络连接';
          clearInterval(this.progressCheckInterval);
          this.progressCheckInterval = null;
          this.btnLoading = false;
          this.btnDisabled = false;
          
          this.$message.error('导入处理失败，请检查网络连接或服务器日志');
        }
      }
    },
    /**
     * 删除文件时的回调
     */
    handleRemove(file, fileList) {
      this.fileList = fileList;
      if (fileList.length === 0) {
        this.file = null;
        this.resetUploadStatus();
      }
    },

    /**
     * 预览文件时的回调
     */
    handlePreview(file) {
      // 文件预览逻辑，如果是Excel文件可能不需要特殊处理
      console.log('预览文件:', file.name);
    },
  },
  components: {
    ElectUsersBox, MenuTree
  },
  created() {
    this.getAllTaskPackage();
    this.selectUser();
    this.getAccountNameList();
    // this.getAgentList();
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.progressCheckInterval) {
      clearInterval(this.progressCheckInterval);
      this.progressCheckInterval = null;
    }
  }
};
</script>

<style scoped>
.hint {
  margin-left: 2vh;
  font-weight: 400;
  font-size: 12px;
  color: red;
}

.popups {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}

.popups .el-main {
  background-color: #fff;
  margin: 15vh auto;
}

.popups .el-main .header {
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}

.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}
</style>
